<?php


namespace app\library\create\lib;


class CreateModel
{
    public $notAllowUpdateFile = ['id', 'update_time', 'create_time', 'ctime'];

    /**
     * @param string $name 文件类型名
     * @param array $tableField
     * @param string $prefix
     */
    public static function buildFile(string $name, array $tableField, string $prefix)
    {
        $self = new self();
        $commonModelFile = root_path('app/library/template') . 'CommonModel.template';
        $str = file_get_contents($commonModelFile);
        $str = str_replace('modelName', $name, $str);
        $str = str_replace('comment', $tableField['comment'], $str);
        $str = str_replace('noticeNameStr', $tableField['comment'], $str);
        list($properties, $canShow, $canUpdate) = $self->getPropertyStr($tableField['fields']);
        $str = str_replace('property', $properties, $str);
        $str = str_replace('canShowFieldsStr', $canShow, $str);
        $str = str_replace('updateFieldsStr', $canUpdate, $str);
        $str = str_replace('tableName', $tableField['tableName'], $str);
        $str = str_replace('tableName', $tableField['tableName'], $str);
        $file = "$name.php";
        $path = root_path('app/model');
        CreateFile::createFile($path, $file, $str); //生成文件
    }


    /**
     * @param array $propertyArr
     * @return array
     */
    public function getPropertyStr(array $propertyArr)
    {
        $str = '';
        $canShow = '';
        $canUpdate = '';
        foreach ($propertyArr as $item) {
            $str .= PHP_EOL;
            $filed = $item['filed'];
            $str .= " * @property " . $item['type'] . ' ' . $filed . ' ' . $item['comment'];
            $canShow .= $canShow != '' ? ',' : '';
            $canShow .= "'" . $filed . "'";
            if (!in_array($filed, $this->notAllowUpdateFile)) {
                $canUpdate .= $canUpdate != '' ? ',' : '';
                $canUpdate .= "'" . $filed . "'";
            }
        }
        return [$str, $canShow, $canUpdate];
    }

}